from django.contrib import admin, messages
from django.db.models import Q
from django.http import HttpResponse

import csv
import logging
from datetime import datetime

from django.utils.safestring import mark_safe

from jobs.models import Resume
from .dingtalk import send
from .models import Candidate
from interview import candidate_fieldset as cf
from .tasks import send_dingtalk_message
# Register your models here.

logger = logging.getLogger(__name__)

exportable_fields = ('username', 'city', 'phone', 'bachelor_school', 'master_school', 'degree',
                     'first_result', 'first_interviewer_user', 'second_result', 'second_interviewer_user', 'hr_result',
                     'hr_score', 'hr_remark', 'hr_interviewer_user')


# 类似有：通知面试官，候选人通过面试；再通知候选人等
def export_model_as_csv(modeladmin, request, queryset):
    response = HttpResponse(content_type='text/csv')
    field_list = exportable_fields
    response['Content-Disposition'] = 'attachment;filename = recruitment-candidates-list-%s.csv' % (
        datetime.now().strftime('%Y-%m-%d-%H-%M-%S'),
    )

    # 写入表头
    writer = csv.writer(response)
    writer.writerow(
        [queryset.model._meta.get_field(f).verbose_name.title() for f in field_list]
    )

    for obj in queryset:
        # 单行的记录(各个字段的值),写入到csv文件
        csv_line_values = []
        for field in field_list:
            field_object = queryset.model._meta.get_field(field)
            field_value = field_object.value_from_object(obj)
            csv_line_values.append(field_value)
        writer.writerow(csv_line_values)

    logger.error('%s export　%d candidate records' % (request.user, len(queryset)))
    return response


export_model_as_csv.short_description = "导出为csv文件"
export_model_as_csv.allowed_permissions = ('export',)


# 通知一面面试官面试
def notify_interviewer(modeladmin, request, queryset):
    candidates = ''
    interviewers = set()  # 方法一：利用集合去重面试官
    interviewers_ = None
    for obj in queryset:
        candidates = obj.username + '; ' + candidates
        # interviewers = obj.first_interviewer_user.username + ';' + interviewers
        if obj.first_interviewer_user is None:  # 增加判断勾选的一面面试官是否都有值
            messages.add_message(request, messages.INFO, '当前勾选中有一面面试官未保存，请先确保全勾选一面面试官并保存后再执行其他操作')
            return

        interviewers.add(obj.first_interviewer_user.username)  # 集合add方法返回值None
        interviewers_ = '; '.join(interviewers)

    # interviewers_ori = []  # 方法二：利用列表去重
    # interviewers_new = []
    # for obj in queryset:
    #     candidates = obj.username + '; ' + candidates
    #     # TODO 当后台登录人员勾选选项后没有点击保存操作，直接去对勾选项执行菜单栏操作，可能会报错,这里判断处理
    #     if obj.first_interviewer_user is None:
    #         messages.add_message(request, messages.INFO,'当前勾选中有一面面试官未保存，请先确保全勾选一面面试官并保存后再执行其他操作')
    #         return
    #     interviewers_ori.append(obj.first_interviewer_user.username)

    # interviewers_ori = [obj.username + '; ' + candidates if obj.first_interviewer_user  else None for obj in queryset ]

    # for _ in interviewers_ori:
    #     if _ not in interviewers_new:
    #         interviewers_new.append(_)
    # interviewers_new = [_ for _ in interviewers_ori if _ not in interviewers_ori]
    # interviewers = '; '.join(interviewers_new)

    # send('共有 %d 位候选人 %s 进入面试环节，\n待面试面试官: %s' % (len(queryset), candidates, interviewers_))  # 未使用celery时
    # TODO Celery服务写入日志文件未实现
    send_dingtalk_message.delay('共有 %d 位候选人 %s 进入面试环节，\n待面试面试官: %s' % (len(queryset), candidates, interviewers_))
    messages.add_message(request, messages.INFO,
                         '共有 %d 位候选人 %s 进入面试环节，\n待面试面试官: %s' % (len(queryset), candidates, interviewers_))


notify_interviewer.short_description = u"通知一面面试官"


class CandidateAdmin(admin.ModelAdmin):
    exclude = ("creator", "created_date", "modified_date",)

    actions = (export_model_as_csv, notify_interviewer)

    # TODO 自定义方法不使用obj参数暂时无法完成
    # def show_origin_resume(self, request):
    #     resume_list = Resume.objects.all()
    #     candidate_list = Candidate.objects.all()
    #     len_resume_list = len(resume_list)
    #     for resume in resume_list:
    #
    #         for candidate in candidate_list:
    #             if resume.phone == candidate.phone:
    #                 # local len_candidate_list
    #                 len_resume_list =len_resume_list - 1
    #                 # print(len_resume_list)
    #                 # print('\n')
    #                 if len_resume_list == 0:
    #                     break
    #                 else:
    #                     print(len_resume_list)
    #                     str1 = '<a href = "/resume/%s" target="_blank">查看简历</a>' % str(resume.id)
    #                     return mark_safe(str1)
    #             else:
    #                 return ''

    def get_resume(self, obj):
        if not obj.phone:
            return ''
        resumes = Resume.objects.filter(phone=obj.phone)
        if resumes and len(resumes) > 0:  # 需考虑重复手机号
            return mark_safe(u'<a href="/resume/%s" target="_blank">%s</a' % (resumes[0].id, "查看简历"))

        return ''

    get_resume.short_description = '查看简历'
    get_resume.allow_tags = True

    # 当前用户是否有导出权限
    def has_export_permission(self, request):
        opts = self.opts
        logger.info('%s.%s' % (opts.app_label, 'export'))  # interview.export
        return request.user.has_perm('%s.%s' % (opts.app_label, 'export'))

    list_display = (
        "username", "city", 'get_resume', "apply_position", "bachelor_school", "first_score", "first_result",
        "first_interviewer_user",
        "second_score", "second_result", "second_interviewer_user", "hr_score", "hr_result", "hr_interviewer_user",
        "last_editor",)

    # 右侧筛选条件
    list_filter = (
        'city', 'first_result', 'second_result', 'hr_result', 'first_interviewer_user', 'second_interviewer_user',
        'hr_interviewer_user')
    # 查询字段
    search_fields = ('username', 'city', 'bachelor_school', 'email',)
    # 列表页排序字段
    ordering = ('hr_result', 'second_result', 'first_result',)

    # 一面面试官能看到一面记录，二面面试官能看到一二面记录，hr能查看应聘者所有面试反馈
    def get_fieldsets(self, request, obj=None):
        """返回指定字段集"""
        group_names = self.get_group_names(request.user)

        if 'interview' in group_names:
            if obj.first_interviewer_user == request.user:
                return cf.default_fieldsets_first
            if obj.second_interviewer_user == request.user:
                return cf.default_fieldsets_second
        return cf.default_fieldsets

    # 专业面试官只能看到自己负责的候选人，hr和超级管理员可以看到所有
    def get_queryset(self, request):  # show data only owned by the user
        """返回列表页的数据集"""
        group_names = self.get_group_names(request.user)
        qs = super(CandidateAdmin, self).get_queryset(request)

        if request.user.is_superuser or 'hr' in group_names:
            return qs
        return Candidate.objects.filter(Q(first_interviewer_user=request.user) |
                                        Q(second_interviewer_user=request.user))

    # HR可以指定候选面试官
    # list_editable = ('first_interviewer_user','second_interviewer_user',)

    # 面试官登录只能查看面试官选项;HR可以修改
    def get_group_names(self, user):
        group_names = []
        for g in user.groups.all():
            group_names.append(g.name)
        return group_names

    def get_readonly_fields(self, request, obj=None):
        group_names = self.get_group_names(request.user)

        if 'interview' in group_names:
            logger.info("%s is in group interview" % request.user.username)
            return ('first_interviewer_user', 'second_interviewer_user',)
        return ()

    # HR在列表页可以直接修改;自定义父类方法get_changelist_instance添加支持
    def get_list_editable(self, request):
        group_names = self.get_group_names(request.user)

        if request.user.is_superuser or 'hr' in group_names:
            return ('first_interviewer_user', 'second_interviewer_user',)
        return ()

    def get_changelist_instance(self, request):
        self.list_editable = self.get_list_editable(request)
        return super(CandidateAdmin, self).get_changelist_instance(request)

    def save_model(self, request, obj, form, change):
        obj.last_editor = request.user.username
        if not obj.last_editor:
            obj.creator = request.user.username
        obj.modified_date = datetime.now()
        obj.save()


admin.site.register(Candidate, CandidateAdmin)
